"use strict";

import axios from "axios";
import qs from "qs";
import { Global, httpResDeal } from "./global";
const APP_TAG = "bjb";
const OUT_TIME = 10000; // 超时时间
const axiosOpts = function(url, data, baseURL, json, forms) {
  let form;
  if (forms) {
    form = new FormData();
    for (let k in data) {
      form.append(k, data[k]);
    }
  } else {
    form = json ? data : qs.stringify(data);
  }
  return {
    baseURL: Global[baseURL || "url"],
    url,
    data: form,
    timeout: OUT_TIME,
    headers: {
      "X-Requested-With": "XMLHttpRequest",
      "Content-Type": json
        ? "application/json"
        : "application/x-www-form-urlencoded; charset=UTF-8"
      // app: APP_TAG
    }
  };
};
axios.interceptors.request.use(
  config => {
    // 这里的config包含每次请求的内容
    // 判断localStorage中是否存在api_token
    if (localStorage.getItem("token")) {
      //  存在将api_token写入 request header
      config.headers.token = localStorage.getItem("token");
    }
    return config;
  },
  err => Promise.reject(err)
);

axios.interceptors.response.use(
  response => response,
  error => Promise.resolve(error.response)
);

function checkStatus(response) {
  // 未登录
  if (response && response.status === 401) {
    return {
      data: { code: 401, message: "未登录或登录已过期" }
    };
  }
  // 文件过大
  if (response && response.status === 413) {
    return {
      data: { code: 413, message: "请求非法" }
    };
  }

  // 如果http状态码正常，则直接返回数据
  if (
    response &&
    (response.status === 200 ||
      response.status === 304 ||
      response.status === 400)
  ) {
    return response;
  }
  // 异常状态下，把错误信息返回去
  return response;
}

// 请求方式的配置
class Axios {
  constructor(vm) {
    this.vm = vm;
  }

  post(url, data, baseURL, json, forms, isUpload) {
    let opts = axiosOpts(url, data, baseURL, json, forms);
    opts.method = "post";
    return this.responseCommon(opts, isUpload);
  }
  get(url, params, baseURL) {
    let opts = axiosOpts(url, params, baseURL);
    opts.method = "get";
    opts.params = params;
    return this.responseCommon(opts);
  }
  put(url, data, baseURL, json, forms) {
    let opts = axiosOpts(url, data, baseURL, json, forms);
    opts.method = "put";
    return this.responseCommon(opts);
  }
  del(url, data, baseURL, json, forms) {
    let opts = axiosOpts(url, data, baseURL, json, forms);
    opts.method = "delete";
    return this.responseCommon(opts);
  }
  responseCommon(opts, isUpload) {
    if (isUpload) {
      opts.onUploadProgress = isUpload;
    }
    return axios(opts)
      .then(checkStatus.bind(this.vm))
      .then(httpResDeal.bind(this.vm));
  }
}
export default Axios;
